/*
 * @Description:
 * @Author: ZY
 * @Date: 2020-12-25 15:03:52
 * @LastEditors: ZY
 * @LastEditTime: 2021-01-11 21:05:18
 */

import { ActionTree, ActionContext } from 'vuex'
import { RootState } from '@/store'
import { PermissionState } from './state'
import { Mutations } from './mutations'
import { PermissionMutationType } from './mutation-types'
import { getRoutersRequest } from '@/apis/user'
import { PermissionActionType } from './action-types'
import Layout from '@/layout/Index.vue'
type AugmentedActionContext = {
    commit<K extends keyof Mutations>(
      key: K,
      payload: Parameters<Mutations[K]>[1],
    ): ReturnType<Mutations[K]>
} & Omit<ActionContext<PermissionState, RootState>, 'commit'>

export const loadView = (view) => { // 路由懒加载
  return () => Promise.resolve(require(`@/views/${view}`).default)
}

export interface Actions {
    [PermissionActionType.ACTION_SET_ROUTES](
      { commit }: AugmentedActionContext
      , roles: string[]): void
}

function filterChildren(childrenMap) { // eslint-disable-line no-unused-vars
  let children = []
  childrenMap.forEach(el => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children))
            return
          }
          children.push(c)
        })
        return
      }
    }
    children = children.concat(el)
  })
  return children
}
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, type = false) { // eslint-disable-line no-unused-vars
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route)
    } else {
      delete route.children
      delete route.redirect
    }
    return true
  })
}
export const actions: ActionTree<PermissionState, RootState> & Actions = {
  async [PermissionActionType.ACTION_SET_ROUTES](
    { commit }: AugmentedActionContext) {
    await getRoutersRequest().then((res) => {
      const rdata = JSON.parse(JSON.stringify(res.data))
      const rewriteRoutes = filterAsyncRouter(rdata, true)
      commit(PermissionMutationType.SET_ROUTES, rewriteRoutes)
    }).catch(err => {
      console.log(err)
    })
  }
}
